package com.bdqn.crm.repository;

import com.bdqn.crm.pojo.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface UserRepository extends JpaRepository<User,Long> {

    public List<User> findByUsrNameAndUsrPassword(String usrName, String usrPassword);

    // 此方法对应User实体中的命名查询
    // 如果希望根据接口方法名来实现数据库操作，则命名为：findUsersByUsrName
    public List<User> findByUsrNameLike(String usrName);

    @Query("select u from User  u where u.usrRoleId=?1")
    public Page<User> findPageByUsrRoleId(Long roleId, Pageable pageable);

    @Query(value = "select u from User u where u.usrRoleId=?1")
    public List<User> findByRoleId(Long roleId); // 注意：SQL面向实体类和属性，语句中不能写表名和字段名

    @Query(value = "select * from sys_user where usr_role_id=?1",nativeQuery = true)
    public List<User> findByRoleId1(Long roleId);
    // 以上两种写法执行的运行的SQL语句区别结果是相同的

    @Query(value = "select u from User u where u.usrRoleId=:roleId")
    public List<User> findByRoleId2(@Param("roleId") Long roleId);

    // 如涉及到删除和修改需要加上@Modifying，也可以根据需要添加@Transactional进行事务的支持、操作超时设置管理等
    @Transactional(timeout = 10) // 对事物的支持、操作超超时设置等
    @Modifying
    @Query(value = "update User u set u.usrName = ?1 where u.usrId = ?2")
    public int modifyNameById(String usrName, Long usrId);

    Page<User> findAll(Specification<User> specification, Pageable pageable);
}
